//
//  LSLPlayerView.m
//  LSL_IJKPlayer
//
//  Created by 大龙 on 18/1/4.
//  Copyright © 2018年 LSL. All rights reserved.
//

#import "LSLPlayerView.h"
#define CurrentScreenWidth                         [[UIScreen mainScreen] bounds].size.width
// 屏幕的高
#define CurrentScreenHeight                        [[UIScreen mainScreen] bounds].size.height


static LSLPlayerView *playerView = nil;

@implementation LSLPlayerView
#pragma mark ---- 创建单例 ----
+ (instancetype)sharePlayerView{
    static dispatch_once_t onceToken;
    _dispatch_once(&onceToken, ^{
        playerView = [[LSLPlayerView alloc] init];
        playerView.backgroundColor = [UIColor whiteColor];
    });
    return playerView;
}

#pragma mark ---- 根据URL创建播放器 ----
- (void)setVideoURL:(NSURL *)Videourl{
    if (self.player) {
        [self resetPlayer];
    }
    
    [self installMovieNotificationObservers];
    
    IJKFFOptions *options = [IJKFFOptions optionsByDefault]; //使用默认配置
    [options setPlayerOptionIntValue:1 forKey:@"videotoolbox"];//设置硬解
    self.player = [[IJKFFMoviePlayerController alloc] initWithContentURL:Videourl withOptions:options]; //初始化播放器，播放在线视频
    self.player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    self.player.view.frame = self.bounds;
    self.player.scalingMode = IJKMPMovieScalingModeAspectFit; //缩放模式
    self.player.shouldAutoplay = YES; //开启自动播放
    self.autoresizesSubviews = YES;
    [self addSubview:self.player.view];
    [self.player prepareToPlay];
    [self initPlayerViewWithState:0];
     [self.mediaControl showAndFadeWith:0];
    [self setEasyPlayerFrame];
    
}

#pragma mark ---- 根据URL创建播放器在TableView上 ----
- (void)setVideoURL:(NSURL *)Videourl AtIndexPath:(NSIndexPath *)indexPath;{
    [self setVideoURL:Videourl];
    self.indexPath = indexPath;
    
    _tapTag = NO; //设置手势添加标识
}

/**
 *  重置player
 */
- (void)resetPlayer{
    
    [self shutDownMediaControl];
    [self.player shutdown];
    [self removeMovieNotificationObservers];
    [self.player.view removeFromSuperview];
    self.player = nil;
}
/**
 *  消除控制器
 */
- (void)shutDownMediaControl{
    _mediaControl.tapGesture.delegate = nil;
    _mediaControl.delegatePlayer = nil;
    [_mediaControl removeFromSuperview];
}
#pragma mark ---- 播放器状态监听 ----
- (void)loadStateDidChange:(NSNotification*)notification
{
    //    MPMovieLoadStateUnknown        = 0,
    //    MPMovieLoadStatePlayable       = 1 << 0,
    //    MPMovieLoadStatePlaythroughOK  = 1 << 1, // Playback will be automatically started in this state when shouldAutoplay is YES
    //    MPMovieLoadStateStalled        = 1 << 2, // Playback will be automatically paused in this state, if started
    
    IJKMPMovieLoadState loadState = _player.loadState;
    
    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStatePlaythroughOK: %d\n", (int)loadState);
        /* 添加手势*/
        if(_tapTag == NO){
            [self initTapGesture];
            [self addPanGesture];
            _tapTag = YES;
        }
        [self showMediaControl];
    } else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
    } else {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}

- (void)moviePlayBackDidFinish:(NSNotification*)notification
{
    //    MPMovieFinishReasonPlaybackEnded,
    //    MPMovieFinishReasonPlaybackError,
    //    MPMovieFinishReasonUserExited
    int reason = [[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
    
    switch (reason)
    {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonUserExited: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: %d\n", reason);
            break;
            
        default:
            NSLog(@"playbackPlayBackDidFinish: ???: %d\n", reason);
            break;
    }
}

- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification
{
    NSLog(@"mediaIsPreparedToPlayDidChange\n");
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification
{
    //    MPMoviePlaybackStateStopped,
    //    MPMoviePlaybackStatePlaying,
    //    MPMoviePlaybackStatePaused,
    //    MPMoviePlaybackStateInterrupted,
    //    MPMoviePlaybackStateSeekingForward,
    //    MPMoviePlaybackStateSeekingBackward
    
    switch (_player.playbackState)
    {
        case IJKMPMoviePlaybackStateStopped: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: stoped", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStatePlaying: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: playing", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStatePaused: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: paused", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStateInterrupted: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: interrupted", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStateSeekingForward:
        case IJKMPMoviePlaybackStateSeekingBackward: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: seeking", (int)_player.playbackState);
            break;
        }
        default: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: unknown", (int)_player.playbackState);
            break;
        }
    }
}

#pragma mark Install Movie Notifications

/* Register observers for the various movie object notifications. */
-(void)installMovieNotificationObservers
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadStateDidChange:)
                                                 name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                 name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackStateDidChange:)
                                                 name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                               object:_player];
}

#pragma mark Remove Movie Notification Handlers

/* Remove the movie notification observers from the movie object. */
-(void)removeMovieNotificationObservers
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerLoadStateDidChangeNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerPlaybackDidFinishNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:_player];
}


#pragma mark- 初始化播放器控制
- (void)initPlayerViewWithState:(int)state{
    
    [self configureVolume];

    
    _mediaControl = [[IJKMediaControl alloc] init];
    _mediaControl.delegatePlayer = self.player;
    self.autoresizesSubviews = YES;
    
    [self addSubview:_mediaControl];
    
    _mediaControl.backgroundColor = [UIColor clearColor];
    [_mediaControl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)));
        make.left.equalTo(self.mas_left).with.offset(0);
        make.right.equalTo(self.mas_right).with.offset(0);
        make.top.equalTo(self.mas_top).with.offset(0);
        make.bottom.equalTo(self.mas_bottom).with.offset(0);
        
    }];
    
    _mediaControl.userInteractionEnabled = YES;
    _mediaControl.overlayPanel.userInteractionEnabled = YES;
    
    /**
     toppanel
     */
    _mediaControl.topPanel = [[UIImageView alloc] init];
    _mediaControl.topPanel.userInteractionEnabled = YES;
    _mediaControl.topPanel.backgroundColor = [Tools colorWithHex:@"000000" alpha:0.45];
    //    _mediaControl.topPanel.image = IMG(@"top_bg.png");
    [_mediaControl.overlayPanel addSubview:_mediaControl.topPanel];
    
    _mediaControl.titleLabel = [[UILabel alloc] init];
    _mediaControl.titleLabel.text = @"dalong";
    _mediaControl.titleLabel.font = [UIFont fontWithName:BoldFontType size:16];
    _mediaControl.titleLabel.textColor = [Tools colorWithHex:@"ffffff" alpha:1.0];
    _mediaControl.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_mediaControl.topPanel addSubview:_mediaControl.titleLabel];
    
    _mediaControl.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mediaControl.shareBtn addTarget:self action:@selector(onClickShare:) forControlEvents:UIControlEventTouchUpInside];
    _mediaControl.shareBtn.hidden = YES;
    [_mediaControl.shareBtn setImage:IMG(@"prtscn.png") forState:UIControlStateNormal];
    [_mediaControl.topPanel addSubview:_mediaControl.shareBtn];
    
    _mediaControl.selectCollectionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mediaControl.selectCollectionBtn addTarget:self action:@selector(onClickselectCollection:) forControlEvents:UIControlEventTouchUpInside];
    [_mediaControl.selectCollectionBtn setTitle:NSLocalizedString(@"anthology", nil) forState: UIControlStateNormal];
    _mediaControl.selectCollectionBtn.titleLabel.font = [UIFont fontWithName:LightFontType size:14];
    _mediaControl.selectDefinitionBtn.titleLabel.textColor = [UIColor whiteColor];
    [_mediaControl.topPanel addSubview:_mediaControl.selectCollectionBtn];
    
    //    _mediaControl.centerPlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [_mediaControl.centerPlayButton addTarget:self action:@selector(onClickPlay:) forControlEvents:UIControlEventTouchUpInside];
    //    [_mediaControl addSubview:_mediaControl.centerPlayButton];
    
    /**
     bottompanel
     */
    _mediaControl.bottomPanel = [[UIImageView alloc] init];
    _mediaControl.bottomPanel.userInteractionEnabled = YES;
    //    _mediaControl.bottomPanel.image = IMG(@"bg.png");
    _mediaControl.bottomPanel.backgroundColor = [Tools colorWithHex:@"000000" alpha:0.45];
    [_mediaControl.overlayPanel addSubview:_mediaControl.bottomPanel];
    
    _mediaControl.midPanel = [[UIView alloc] init];
    _mediaControl.midPanel.userInteractionEnabled = YES;
//    _mediaControl.midPanel.backgroundColor =[UIColor blueColor];
    
    [_mediaControl.overlayPanel addSubview:_mediaControl.midPanel];

    
    _mediaControl.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mediaControl.playButton addTarget:self action:@selector(onClickPlay:) forControlEvents:UIControlEventTouchUpInside];
    _mediaControl.playButton.selected = YES;
    [_mediaControl.playButton setImage:IMG(@"play.png") forState:UIControlStateNormal];
    [_mediaControl.playButton setImage:IMG(@"stop.png") forState:UIControlStateSelected];
    [_mediaControl.bottomPanel addSubview:_mediaControl.playButton];
    
    
    _mediaControl.mediaProgressSlider = [[CustomSlider alloc] init];
    //    _mediaControl.mediaProgressSlider.backgroundColor = [UIColor orangeColor];
    //    _mediaControl.mediaProgressSlider.delegate = self;
    [_mediaControl.mediaProgressSlider addTarget:self action:@selector(didSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [_mediaControl.mediaProgressSlider addTarget:self action:@selector(didSliderTouchCancel:) forControlEvents:UIControlEventTouchCancel];
    [_mediaControl.mediaProgressSlider addTarget:self action:@selector(didSliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    [_mediaControl.mediaProgressSlider addTarget:self action:@selector(didSliderTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [_mediaControl.mediaProgressSlider addTarget:self action:@selector(didSliderTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
    
    [_mediaControl.mediaProgressSlider setMinimumTrackImage:[IMG(@"blue.png") stretchableImageWithLeftCapWidth:1 topCapHeight:1] forState:UIControlStateNormal];
    [_mediaControl.mediaProgressSlider setMaximumTrackImage:[IMG(@"white.png") stretchableImageWithLeftCapWidth:1 topCapHeight:1]forState:UIControlStateNormal];
    
    
    [_mediaControl.mediaProgressSlider setThumbImage:IMG(@"spot.png") forState:UIControlStateNormal];//设置了普通状态和高亮状态的滑轮样式
    [_mediaControl.mediaProgressSlider setThumbImage:IMG(@"spot.png") forState:UIControlStateHighlighted];//设置了普通状态和高亮状态的滑轮样式
    
    _mediaControl.mediaProgressSlider.trackBackgoundColor = [UIColor redColor];
    //    _mediaControl.mediaProgressSlider.progressBackgoundColor = [UIColor greenColor];
    //    _mediaControl.mediaProgressSlider.playProgressBackgoundColor = [UIColor yellowColor];
    
    _mediaControl.mediaProgressSlider.continuous = YES;
    [_mediaControl.bottomPanel addSubview:_mediaControl.mediaProgressSlider];
    
    /**
     *  mediaProgressSlider 增加手势
     */
    _mediaControl.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapGesture:)];
    [_mediaControl.mediaProgressSlider addGestureRecognizer:_mediaControl.tapGesture];
    
    
    
    
    
    
    
    _mediaControl.currentTimeLabel = [[UILabel alloc] init];
    _mediaControl.currentTimeLabel.font = [UIFont fontWithName:LightFontType size:11];
    _mediaControl.currentTimeLabel.textColor = [Tools colorWithHex:@"ffffff" alpha:0.5];
    _mediaControl.currentTimeLabel.textAlignment = NSTextAlignmentCenter;
    [_mediaControl.bottomPanel addSubview:_mediaControl.currentTimeLabel];
    
    _mediaControl.totalDurationLabel = [[UILabel alloc] init];
    _mediaControl.totalDurationLabel.font = [UIFont fontWithName:LightFontType size:11];
    _mediaControl.totalDurationLabel.textColor = [Tools colorWithHex:@"ffffff" alpha:0.5];
    _mediaControl.totalDurationLabel.textAlignment = NSTextAlignmentCenter;
    [_mediaControl.bottomPanel addSubview:_mediaControl.totalDurationLabel];
    
    _mediaControl.selectDefinitionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _mediaControl.fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_mediaControl.fullScreenBtn setImage:IMG(@"full.png") forState:UIControlStateNormal];
    [_mediaControl.fullScreenBtn setImage:IMG(@"full.png") forState:UIControlStateHighlighted];
    [_mediaControl.fullScreenBtn addTarget:self action:@selector(onClickfullScreen) forControlEvents:UIControlEventTouchUpInside];
    [_mediaControl.bottomPanel addSubview:_mediaControl.fullScreenBtn];
    
    _defaultBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_defaultBackBtn addTarget:self action:@selector(onClickBack:) forControlEvents:UIControlEventTouchUpInside];
    [_defaultBackBtn setImage:IMG(@"full_back.png") forState:UIControlStateNormal];
    [self addSubview:_defaultBackBtn];

    
#if SCREENCONTROL
    _mediaControl.lockBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //_mediaControl.lockBtn.backgroundColor = [UIColor cyanColor];
    [_mediaControl.lockBtn setBackgroundImage:IMG(@"unlock-nor.png") forState:UIControlStateNormal];
    [_mediaControl.lockBtn setBackgroundImage:IMG(@"lock-nor.png") forState:UIControlStateSelected];
    
    [_mediaControl.lockBtn addTarget:self action:@selector(onClickLock) forControlEvents:UIControlEventTouchUpInside];
    [_mediaControl.midPanel addSubview:_mediaControl.lockBtn];
    _mediaControl.lockBtn.hidden = YES;
#else
    
#endif
    

    

    _mediaControl.hidden = NO;
    //    }
    
    //    _mediaControl.playButton.backgroundColor = [UIColor greenColor];
    //    _mediaControl.pauseButton.backgroundColor = [UIColor blueColor];
    //    _mediaControl.currentTimeLabel.backgroundColor = [UIColor yellowColor];
    //    _mediaControl.totalDurationLabel.backgroundColor = [UIColor greenColor];
    //    _mediaControl.mediaProgressSlider.backgroundColor = [UIColor blueColor];
    //    _mediaControl.fullScreenBtn.backgroundColor = [UIColor redColor];
    
//    [self bringSubviewToFront:_loadingView];
    
    
    // 亮度指示器
    [self addSubview:self.brightnessIndicatorView];
    
//    [_brightnessIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.mas_equalTo(_volumeViewSlider);
//    }];
//    self.brightnessIndicatorView.frame = CGRectMake(0, 0, 155, 155);
//    self.brightnessIndicatorView.center = CGPointMake(CurrentScreenWidth * 0.5, (CurrentScreenHeight - 10) * 0.5);
//     self.brightnessIndicatorView.center = self.center;
    
//    self.brightnessIndicatorView.layer.cornerRadius  = 10;
//    self.brightnessIndicatorView.layer.masksToBounds = YES;

    // 音量指示器
    [self addSubview:self.volumeIndicatorView];
    
   //为亮度条添加毛玻璃
//    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:_brightnessIndicatorView.bounds];
//    toolbar.alpha = 0.97;
//    [_brightnessIndicatorView addSubview:toolbar];
//    [_brightnessIndicatorView sendSubviewToBack:toolbar];
//    
}

#pragma mark- 设置小播放器 frame
- (void)setEasyPlayerFrame
{
    
    [_mediaControl.playButton setImage:IMG(@"play.png") forState:UIControlStateNormal];
    [_mediaControl.playButton setImage:IMG(@"stop.png") forState:UIControlStateSelected];
    
    _mediaControl.shareBtn.hidden = YES;
    
    _mediaControl.selectDefinitionBtn.hidden = YES;
    _mediaControl.selectCollectionBtn.hidden = YES;
    
    _mediaControl.titleLabel.hidden = YES;
#if SCREENCONTROL
    
#else
    _mediaControl.fullScreenBtn.hidden = NO;
#endif
    
    
    //    [_mediaControl.playButton setImage:IMG(@"play-1.png") forState:UIControlStateNormal];
    //    [_mediaControl.pauseButton setImage:nil forState:UIControlStateNormal];
    //    [_mediaControl.playButton setImage:IMG(@"play-1.png") forState:UIControlStateHighlighted];
    //    [_mediaControl.pauseButton setImage:nil forState:UIControlStateHighlighted];
    
    //    _mediaControl.bottomPanel.image = IMG(@"bg.png");
//    _mediaControl.topPanel.backgroundColor = [UIColor clearColor];
    
    [self.player.view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)));
        make.left.equalTo(self.mas_left).with.offset(0);
        make.right.equalTo(self.mas_right).with.offset(0);
        make.top.equalTo(self.mas_top).with.offset(0);
        make.bottom.equalTo(self.mas_bottom).with.offset(0);
    }];
    
    
    [_mediaControl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)));
        make.left.equalTo(self.mas_left).with.offset(0);
        make.right.equalTo(self.mas_right).with.offset(0);
        make.top.equalTo(self.mas_top).with.offset(0);
        make.bottom.equalTo(self.mas_bottom).with.offset(0);
        
    }];
    

    
    /**
     *  @brief  标题栏
     *
     */
    [_mediaControl.topPanel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mediaControl.overlayPanel.mas_left).with.offset(0);
        make.top.equalTo(_mediaControl.overlayPanel.mas_top).with.offset(0);
        make.right.equalTo(_mediaControl.overlayPanel.mas_right).with.offset(0);
        make.height.equalTo(@44);
    }];
    
    
    /**
     *  @brief  播放控制
     *
     */
    
    
    //    [_mediaControl.centerPlayButton mas_remakeConstraints:^(MASConstraintMaker *make) {
    //        make.size.equalTo(_mediaControl.frame.size);
    //        make.center.equalTo(_mediaControl.center);
    //    }];
    
    [_mediaControl.bottomPanel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mediaControl.overlayPanel.mas_left).with.offset(0);
        make.bottom.equalTo(_mediaControl.overlayPanel.mas_bottom).with.offset(0);
        make.right.equalTo(_mediaControl.overlayPanel.mas_right).with.offset(0);
        make.height.equalTo(@40);
    }];
    
    [_mediaControl.midPanel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mediaControl.overlayPanel.mas_left).with.offset(0);
        make.right.equalTo(_mediaControl.overlayPanel.mas_right).with.offset(0);
        make.bottom.equalTo(_mediaControl.bottomPanel.mas_top).with.offset(0);
        make.top.equalTo(_mediaControl.topPanel.mas_bottom).with.offset(0);
    }];
    
    [_mediaControl.playButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.left.equalTo(_mediaControl.overlayPanel.mas_left).with.offset(5);
        make.centerY.mas_equalTo(_mediaControl.bottomPanel.mas_centerY);
    }];
    
    [_mediaControl.mediaProgressSlider mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_mediaControl.currentTimeLabel.mas_right).with.offset(3);
        make.right.equalTo(_mediaControl.totalDurationLabel.mas_left).with.offset(-3);
        make.centerY.mas_equalTo(_mediaControl.bottomPanel.mas_centerY);
        make.height.equalTo(@40);
    }];
    
    [_mediaControl.currentTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 15));
        make.left.equalTo(_mediaControl.playButton.mas_right).with.offset(0);
        make.centerY.mas_equalTo(_mediaControl.bottomPanel.mas_centerY);
    }];
    
    [_mediaControl.totalDurationLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 15));
        make.right.equalTo(_mediaControl.fullScreenBtn.mas_left).with.offset(0);
        make.centerY.mas_equalTo(_mediaControl.bottomPanel.mas_centerY);
    }];
    
    [_mediaControl.fullScreenBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.right.equalTo(_mediaControl.bottomPanel.mas_right).with.offset(-8);
        make.centerY.mas_equalTo(_mediaControl.bottomPanel.mas_centerY);
    }];
    
    [_defaultBackBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(0);
        make.top.equalTo(self.mas_top).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];

    
    
}


#pragma mark- 播放控制事件
- (void)onClickPlay:(id)sender
{
    if (_mediaControl.playButton.selected) {
        [self.player pause];
    }else{
        [self.player play];
    }
    
    [_mediaControl refreshMediaControlWith:0];
}

- (void)onClickPause:(id)sender
{
    [self.player pause];
    
    [_mediaControl refreshMediaControlWith:0];
}


#pragma mark ---- 全屏按钮 ----
- (void)onClickfullScreen{
    [UIDevice setOrientation:UIInterfaceOrientationLandscapeRight];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    
    
}
#pragma mark ---- 返回按钮 ----
- (void)onClickBack:(UIButton *)sender{
    
    [UIDevice setOrientation:UIInterfaceOrientationPortrait];
     if (_delegate && [_delegate respondsToSelector:@selector(returnPlayViewOnCellWithIndexPath:)]) {
         [_delegate returnPlayViewOnCellWithIndexPath:_indexPath];
         
     }
    
    
    
}
#pragma mark ---- 进度条控制 ----
- (void)didSliderTouchDown:(UISlider *)slider
{
    [_mediaControl beginDragMediaSlider];
    /**
     *  取消mediaControl 定时器
     */
    [_mediaControl cancelDelayedHide];
    _mediaControl.tapGesture.enabled = NO;
    
}

- (void)didSliderTouchCancel:(UISlider *)slider
{
    self.player.currentPlaybackTime = (double)_mediaControl.mediaProgressSlider.value;
    _mediaControl.tapGesture.enabled = YES;
    
    [_mediaControl endDragMediaSlider];
    
    [_mediaControl continueDragMediaSliderWith:0];
}


- (void)didSliderTouchUpOutside:(UISlider *)slider
{
    self.player.currentPlaybackTime = (double)_mediaControl.mediaProgressSlider.value;
    _mediaControl.tapGesture.enabled = YES;
    
    [_mediaControl endDragMediaSlider];
    
    [_mediaControl continueDragMediaSliderWith:0];
}

- (void)didSliderTouchUpInside:(UISlider *)slider
{
    self.player.currentPlaybackTime = (double)_mediaControl.mediaProgressSlider.value;
    
    
    [_mediaControl endDragMediaSlider];
    _mediaControl.tapGesture.enabled = YES;
}


- (void)didSliderValueChanged:(UISlider *)slider
{
    NSLog(@"dalong");
    
    
    //    self.player.currentPlaybackTime = (double)_mediaControl.mediaProgressSlider.curValue;
    [_mediaControl continueDragMediaSliderWith:0];
    
    
    
}


#pragma mark ---- 进度条点击事件 ----
-(void)sliderTapGesture:(UITapGestureRecognizer *)sender{
    NSLog(@"@@@@@@");
    CGPoint touchPoint = [sender locationInView:_mediaControl.mediaProgressSlider];
    CGFloat value = (_mediaControl.mediaProgressSlider.maximumValue - _mediaControl.mediaProgressSlider.minimumValue) * (touchPoint.x / _mediaControl.mediaProgressSlider.frame.size.width );
    [_mediaControl.mediaProgressSlider setValue:value];
    
    [self didSliderTouchUpInside:_mediaControl.mediaProgressSlider];
    
}

#pragma mark - 屏幕滑动手势方法

- (void)addPanGesture
{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panDirection:)];
    pan.delegate                = self;
    [_mediaControl.midPanel addGestureRecognizer:pan];
    
    
}



/**
 *  pan手势事件
 *
 *  @param pan UIPanGestureRecognizer
 */
- (void)panDirection:(UIPanGestureRecognizer *)pan
{
    //根据在view上Pan的位置，确定是调音量还是亮度
    //    NSLog(@"******%@",[pan.view class]);
    CGPoint locationPoint = [pan locationInView:_mediaControl.midPanel];
    
    // 我们要响应水平移动和垂直移动
    // 根据上次和本次移动的位置，算出一个速率的point
    CGPoint veloctyPoint = [pan velocityInView:_mediaControl.midPanel];
#if DALONGTEST
    
#else
    
#endif
    
    
    
    // 判断是垂直移动还是水平移动
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{ // 开始移动
#if DALONGTEST
            
            
            self.playTimeNow = self.player.currentPlaybackTime;
            [_mediaControl cancelDelayedHide];
            
            
#else
            
#endif
            // 使用绝对值来判断移动的方向
            CGFloat x = fabs(veloctyPoint.x);
            CGFloat y = fabs(veloctyPoint.y);
            if (x > y) {
                
                
                
                // 水平移动
                
                // 取消隐藏
                //                self.controlView.horizontalLabel.hidden = NO;
                self.panDirection = PanDirectionHorizontalMoved;

            }
            else if (x < y){ // 垂直移动
                
                self.panDirection = PanDirectionVerticalMoved;
                // 开始滑动的时候,状态改为正在控制音量
                if (locationPoint.x > self.bounds.size.width / 2) {
                    self.isVolume = YES;
                }else { // 状态改为显示亮度调节
                    self.isVolume = NO;
                }
            }
            break;
        }
        case UIGestureRecognizerStateChanged:{ // 正在移动
            switch (self.panDirection) {
                case PanDirectionHorizontalMoved:{
                    
                    [self horizontalMoved:veloctyPoint.x]; // 水平移动的方法只要x方向的值
                    //                    NSLog(@"水平移动 %f,%f",veloctyPoint.x,locationPoint.x);
                    break;
                }
                case PanDirectionVerticalMoved:{
                    [self verticalMoved:veloctyPoint.y]; // 垂直移动方法只要y方向的值
                    if (self.isVolume) {
                        NSLog(@"音量垂直移动 %f",veloctyPoint.y);
                    }else{
                        NSLog(@"亮度垂直移动 %f",veloctyPoint.y);
                    }
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case UIGestureRecognizerStateEnded:{ // 移动停止
            // 移动结束也需要判断垂直或者平移
            // 比如水平移动结束时，要快进到指定位置，如果这里没有判断，当我们调节音量完之后，会出现屏幕跳动的bug
            [_mediaControl endDragMediaSlider];
            switch (self.panDirection) {
                case PanDirectionHorizontalMoved:{

                    break;
                }
                case PanDirectionVerticalMoved:{

                    break;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
}

/**
 *  pan垂直移动的方法
 *
 *  @param value void
 */
- (void)verticalMoved:(CGFloat)value
{
    self.isVolume ? (self.volumeViewSlider.value -= value / 10000) : ([UIScreen mainScreen].brightness -= value / 10000);
}

/**
 *  pan水平移动的方法
 *
 *  @param value void
 */
- (void)horizontalMoved:(CGFloat)value
{
    
    return;
    
    
    
    
}
/**
 *  亮度View懒加载
 *
 */
- (ZXVideoPlayerBrightnessView *)brightnessIndicatorView
{
    if (!_brightnessIndicatorView) {
//        _brightnessIndicatorView = [[ZXVideoPlayerBrightnessView alloc] initWithFrame:CGRectMake(0, 0, kVideoBrightnessIndicatorViewSide, kVideoBrightnessIndicatorViewSide)];
        _brightnessIndicatorView = [[ZXVideoPlayerBrightnessView alloc] init];
    }
    return _brightnessIndicatorView;
}

/**
 *  音量View懒加载
 *
 */

- (ZXVideoPlayerVolumeView *)volumeIndicatorView
{
    if (!_volumeIndicatorView) {
        _volumeIndicatorView = [[ZXVideoPlayerVolumeView alloc] initWithFrame:CGRectMake(0, 0, kVideoVolumeIndicatorViewSide, kVideoVolumeIndicatorViewSide)];
    }
    return _volumeIndicatorView;
}

/**
 *  获取系统音量
 */
- (void)configureVolume
{
    
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    _volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            _volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    
    // 使用这个category的应用不会随着手机静音键打开而静音，可在手机静音下播放声音
    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance]
                    setCategory: AVAudioSessionCategoryPlayback
                    error: &setCategoryError];
    
    if (!success) { /* handle the error in setCategoryError */ }
    
    // 监听耳机插入和拔掉通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];
}

/**
 *  耳机插入、拔出事件
 */
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    
    switch (routeChangeReason) {
            
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            // 耳机插入
            break;
            
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
        {
            // 耳机拔掉
            // 拔掉耳机继续播放
            //            [self play];
        }
            break;
            
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}

#pragma mark ---- 亮度条 ----
- (void)layoutSubviews{
    [super layoutSubviews];
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
        _brightnessIndicatorView.center = CGPointMake(CurrentScreenWidth * 0.5, (CurrentScreenHeight - 10) * 0.5);
    } else {
        _brightnessIndicatorView.center = CGPointMake(CurrentScreenWidth * 0.5, CurrentScreenHeight * 0.5);
    }
    
    _brightnessIndicatorView.brightnessImageView.center = CGPointMake(155 * 0.5, 155 * 0.5);
    
}







#pragma mark- 初始化点击手势 ----
- (void)initTapGesture
{
    UITapGestureRecognizer *showControl = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMediaControl)];
    showControl.numberOfTapsRequired = 1; // 单击
    [_mediaControl addGestureRecognizer:showControl];
    
    UITapGestureRecognizer *hideControl = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMediaControl:)];
    hideControl.numberOfTapsRequired = 1; // 单击
    [_mediaControl.overlayPanel addGestureRecognizer:hideControl];
    
    
    //    UITapGestureRecognizer *hideControl1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMediaControl:)];
    //    hideControl1.numberOfTapsRequired = 1; // 单击
    //    [_mediaControl.midPanel addGestureRecognizer:hideControl1];
    
    
    
}
#pragma mark- 显示隐藏 media control

- (void)showMediaControl
{
    
    [_mediaControl endDragMediaSlider];
    
    [_mediaControl showAndFadeWith:1];
    //    [_mediaControl cancelDelayedHide];
    //        if (authenState != 0) {
    //            [self  performSelector:@selector(hideMediaControl) withObject:nil afterDelay:5];
    //
    //        }
    
    
    
}

- (void)hideMediaControl
{
    [_mediaControl endDragMediaSlider];
    [_mediaControl hide];

}

- (void)hideMediaControl:(UITapGestureRecognizer *)sender{
    [_mediaControl endDragMediaSlider];
    if ([NSStringFromClass([sender.view class] ) isEqualToString:@"UISlider"]) {
        
    }else{
           [_mediaControl hide];
        }
    
}

#pragma mark - 屏幕方向改变的监听
//屏幕方向改变时的监听
- (void)orientChange:(NSNotification *)notification{
    UIDeviceOrientation orient = [[UIDevice currentDevice] orientation];
    switch (orient) {
        case UIDeviceOrientationPortrait:            // Device oriented vertically, home button on the bottom
        {
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
            
            [self layoutSubviews];
        }
            break;
        case UIDeviceOrientationLandscapeLeft:      // Device oriented horizontally, home button on the right
        {

            [[UIApplication sharedApplication] setStatusBarHidden:YES];
            self.frame = self.window.bounds;

            [self layoutSubviews];
        }
            break;
        case UIDeviceOrientationLandscapeRight:      // Device oriented horizontally, home button on the left
        {

            [[UIApplication sharedApplication] setStatusBarHidden:YES];
            self.frame = self.window.bounds;

            
            [self layoutSubviews];
        }
            break;
        default:
            break;
    }
}
#pragma mark ---- 滑动UIGestureRecognizerDelegate ----
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    //    NSLog(@"#####%@",gestureRecognizer.view);
    return YES;
}










/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


@end
